package com.lagou.work1;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/*
    flink入门案例 wordcount 流处理java版
 */
public class WordCountJavaStreaming {
    public static void main(String[] args) throws Exception {
        //获取flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //获取数据
        DataStreamSource<String> text = env.socketTextStream("server1", 9099);
        //对数据进行处理
        SingleOutputStreamOperator<Tuple2<String, Integer>> data = text.flatMap(new SplitClz());
        //对切分拼接后的数据进行key聚合，累加
        SingleOutputStreamOperator<Tuple2<String, Integer>> operator = data.keyBy(0).sum(1);
        //输出结果
        operator.print();
        env.execute();
    }

    //对数据进行切分，拼接处理
    private static class SplitClz implements FlatMapFunction<String, Tuple2<String,Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] s1 = s.split(" ");
            for(String word : s1) {
                collector.collect(new Tuple2<String, Integer>(word,1));
            }
        }
    }
}
